<template>
	<div class="content-box add-good-argument">
		<el-form ref="formRef" class="good-store-form" :model="form" :rules="rules" label-width="100px">
			<el-form-item label="门店名称" prop="name">
				<el-input v-model="form.name" placeholder="输入门店名称" :maxlength="30" />
			</el-form-item>
			<el-form-item label="门店编码" prop="code">
				<el-input v-model="form.code" placeholder="输入门店编码" :maxlength="30" />
			</el-form-item>
			<el-form-item label="门店类型" prop="type">
				<el-checkbox-group v-model="form.type">
					<el-checkbox v-for="item in typeOptions" :key="item.id" :label="item.id" :value="item.id">{{ item.name }}</el-checkbox>
				</el-checkbox-group>
			</el-form-item>
			<el-form-item label="门店Logo" prop="logo">
				<uploadImage v-model:file-list="form.logo" :limit="1" :fileSize="500 / 1024">
					<template #tip> 建议尺寸：800*800像素，500kb以下，jpg、png格式。 </template>
				</uploadImage>
			</el-form-item>
			<el-form-item label="门店状态" prop="isopen">
				<el-radio-group v-model="form.isopen" class="w-full">
					<el-radio :value="1"> 启用 </el-radio>
					<el-radio :value="0"> 禁用 </el-radio>
				</el-radio-group>
			</el-form-item>
			<el-form-item label="门店地址" prop="address">
				<vueMap v-model="form.address"></vueMap>
			</el-form-item>
			<el-form-item label="客服电话" prop="phone">
				<el-input v-model="form.phone" placeholder="输入客服电话" :maxlength="30" />
			</el-form-item>
			<el-form-item label="营业时间" prop="time">
				<el-time-picker
					v-model="form.time"
					format="HH:mm"
					value-format="HH:mm"
					is-range
					range-separator="至"
					start-placeholder="开店时间"
					end-placeholder="闭店时间"
				/>
			</el-form-item>
			<el-form-item label-width="0">
				<div class="flex-start w-full">
					<el-button @click="back">取消</el-button>
					<el-button type="primary" v-debounce="onSubmit">保存</el-button>
				</div>
			</el-form-item>
		</el-form>
	</div>
</template>

<script setup lang="tsx">
import { FormRules, ElMessage, dayjs } from 'element-plus';
import { ref, reactive, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { fetchCreateStore, fetchUpdateStore, fetchStoreDetail, fetchStoreTypeList } from '/@/api/store';
import uploadImage from '/@/components/upload/image.vue';
import vueMap from '/@/components/vueMap/index.vue';

const route = useRoute();
const router = useRouter();

const formRef = ref();
const form = ref<any>({
	name: '',
	code: '',
	logo: [],
	type: [],
	details: [],
});

const editId = ref();
const typeOptions = ref<any[]>([]);

//校验规则
const rules = reactive<FormRules<any>>({
	name: [{ required: true, trigger: 'blur', message: '门店名称不能为空' }],
	code: [{ required: true, trigger: 'blur', message: '门店编码不能为空' }],
	type: [{ required: true, trigger: ['blur', 'change'], message: '门店类型不能为空' }],
	isopen: [{ required: true, trigger: 'blur', message: '门店状态不能为空' }],
	phone: [
		{ required: true, message: '输入客服电话', trigger: 'blur' },
		{
			pattern:
				/((\d{11})|^((\d{7,8})|(\d{4}|\d{3})-(\d{7,8})|(\d{4}|\d{3})-(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1})|(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1}))$)/,
			message: '请输入有效的电话号码',
			trigger: 'blur',
		},
	],
	address: [{ required: true, trigger: ['blur', 'change'], message: '门店地址不能为空' }],
	time: [{ required: true, trigger: ['blur', 'change'], message: '营业时间不能为空' }],
});

const onSubmit = async () => {
	formRef.value.validate(async (valid: boolean) => {
		if (valid) {
			const params = { ...form.value };
			params.province = params.address.city[0];
			params.city = params.address.city[1];
			params.district = params.address.city[2];
			params.locationDetail = params.address.locationDetail;
			params.longitude = params.address.coord[0];
			params.latitude = params.address.coord[1];
			params.openTime = params.time[0];
			params.closeTime = params.time[1];
			params.type = params.type.join();
			params.logo = params.logo.map((v: any) => v.url).join(',');

			const res = editId.value ? await fetchUpdateStore(params) : await fetchCreateStore(params);
			if (res.code == 200) {
				ElMessage.success(editId.value ? '编辑门店成功' : '新增门店成功');
				back();
			} else {
				ElMessage.error(res.msg);
			}
		}
	});
};

const back = () => {
	router.push('/store/list');
};

const initData = async () => {
	const res = await fetchStoreTypeList({ page: 1, size: 99999 });
	if (res.code == 200) {
		typeOptions.value = res.data.records;
	}
	editId.value = route.params?.id;
	if (editId.value) {
		const res = await fetchStoreDetail({ id: editId.value });
		if (res.code === 200) {
			const data = res.data.shop;
			data.type = data.type.split(',').map((v: any) => Number(v));
			data.isopen = data.isopen ? 1 : 0;
			data.address = {
				city: [data.province, data.city, data.district],
				locationDetail: data.locationDetail,
				coord: [data.longitude, data.latitude],
			};
			data.logo = data.logo ? data.logo.split(',').map((url: any) => ({ url })) : [];
			data.time = [data.openTime, data.closeTime];
			form.value = data;
		}
	}
};

onMounted(() => {
	initData();
});
</script>

<style lang="scss">
.good-store-form {
	.el-form-item {
		.el-input,
		.el-select,
		.el-input-number,
		.el-cascader,
		.el-date-editor {
			width: 100%;
			max-width: 450px;
		}
	}
	.el-table {
		.el-form-item {
			width: 80%;
			max-width: 150px;
			margin: auto;
		}
	}
}
</style>
